import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('../views/Layout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { 
          title: '首页',
          roles: ['Administrator', 'Teacher', 'Student']
        }
      },
      {
        path: '/students',
        name: 'Students',
        component: () => import('../views/Students.vue'),
        meta: { 
          title: '学生管理',
          roles: ['Administrator', 'Teacher']
        }
      },
      {
        path: '/courses',
        name: 'Courses',
        component: () => import('../views/Courses.vue'),
        meta: { 
          title: '课程管理',
          roles: ['Administrator', 'Teacher']
        }
      },
      {
        path: '/enrollments',
        name: 'Enrollments',
        component: () => import('../views/Enrollments.vue'),
        meta: { 
          title: '选课管理',
          roles: ['Administrator', 'Teacher', 'Student']
        }
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('../views/Users.vue'),
        meta: { 
          title: '用户管理',
          roles: ['Administrator']
        }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue'),
        meta: { 
          title: '个人中心',
          roles: ['Administrator', 'Teacher', 'Student']
        }
      },
      {
        path: '/student-credits',
        name: 'StudentCredits',
        component: () => import('../views/StudentCredits.vue'),
        meta: { 
          title: '学生学分统计',
          roles: ['Administrator', 'Teacher']
        }
      },
      {
        path: '/ai-query',
        name: 'AiQuery',
        component: () => import('../views/AiQuery.vue'),
        meta: { 
          title: '智能查询',
          roles: ['Administrator', 'Teacher', 'Student']
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const userStore = useUserStore()
  
  // 如果访问登录页且已有token，根据用户角色跳转到合适页面
  if (to.path === '/login' && token) {
    if (userStore.userInfo) {
      const userRole = userStore.userInfo.role
      if (userRole === 'Student') {
        next('/enrollments')
      } else if (userRole === 'Teacher') {
        next('/courses')
      } else {
        next('/dashboard')
      }
    } else {
      next('/dashboard')
    }
    return
  }
  
  // 如果需要认证但没有token，跳转到登录页
  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  }
  
  // 如果不需要认证，直接通过
  if (!to.meta.requiresAuth) {
    next()
    return
  }
  
  // 如果有token但没有用户信息，尝试获取用户信息
  if (token && !userStore.userInfo) {
    try {
      await userStore.fetchUserInfo()
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // token可能已过期，清除并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      userStore.logout()
      next('/login')
      return
    }
  }
  
  // 检查角色权限
  if (to.meta.roles && userStore.userInfo) {
    const userRole = userStore.userInfo.role
    if (!to.meta.roles.includes(userRole)) {
      ElMessage.error('您没有权限访问该页面')
      // 根据用户角色跳转到有权限的页面
      let redirectPath
      if (userRole === 'Student') {
        redirectPath = '/enrollments'
      } else if (userRole === 'Teacher') {
        redirectPath = '/courses'
      } else if (userRole === 'Administrator') {
        redirectPath = '/dashboard'
      } else {
        // 未知角色，跳转到登录页
        next('/login')
        return
      }
      
      // 避免重定向到当前页面造成循环
      if (to.path !== redirectPath) {
        next(redirectPath)
      } else {
        // 如果要跳转的页面就是当前页面，说明用户没有任何可访问的页面
        ElMessage.error('您的账户权限异常，请联系管理员')
        next('/login')
      }
      return
    }
  }
  
  next()
})

export default router
